package com.saltedfish.tool.wxapi;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;

import com.saltedfish.tool.constant.StringConstant;
import com.saltedfish.tool.model.ThirdLoginInfo;
import com.tencent.mm.opensdk.modelbase.BaseReq;
import com.tencent.mm.opensdk.modelbase.BaseResp;
import com.tencent.mm.opensdk.modelmsg.SendAuth;
import com.tencent.mm.opensdk.openapi.IWXAPIEventHandler;
import com.tencent.mm.opensdk.openapi.WXAPIFactory;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;

import cn.droidlover.xdroidmvp.event.BusProvider;
import cn.droidlover.xdroidmvp.log.XLog;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

public class WXEntryActivity extends Activity implements IWXAPIEventHandler{
	private static String TAG = "MicroMsg.WXEntryActivity";
	private ThirdLoginInfo loginInfo;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
		StringConstant.wx_api = WXAPIFactory.createWXAPI(this, StringConstant.APP_ID, true);
		StringConstant.wx_api.registerApp(StringConstant.APP_ID);
		StringConstant.wx_api.handleIntent(getIntent(), this);



	}

	@Override
	protected void onNewIntent(Intent intent) {
		super.onNewIntent(intent);
		
	}

	@Override
	public void onReq(BaseReq req) {
		switch (req.getType()) {

		default:
			break;
		}
        finish();
	}

	@Override
	public void onResp(BaseResp resp) {
		switch (resp.errCode) {
			case BaseResp.ErrCode.ERR_OK:
				XLog.e("wx Info", "onResp OK"+resp.openId);
				if (resp instanceof SendAuth.Resp) {
					SendAuth.Resp newResp = (SendAuth.Resp) resp;
					//获取微信传回的code
					String code = newResp.code; //到这我们就获得code值了，可以进行下面自己服务器的操作了

//					XLog.e("wx Info",code+"---onResp OK---->>>"+newResp.toString());
					loginInfo = new ThirdLoginInfo();
					loginInfo.setCode(code);
					loginInfo.loginType = 1;
					XLog.e("wx Info",code+"---onResploginInfo---->>>"+loginInfo.toString());

					BusProvider.getBus().post(loginInfo);
					finish();

					//获取用户信息
				//	getAccessToken(code);

//				}else {
//					finish();
				}
				break;
			case BaseResp.ErrCode.ERR_USER_CANCEL:
				XLog.e("wx Info","onResp ERR_USER_CANCEL ");
				//发送取消
				break;
			case BaseResp.ErrCode.ERR_AUTH_DENIED:
				XLog.e("wx Info","onResp ERR_AUTH_DENIED");
				//发送被拒绝
				break;
			default:
				XLog.e("wx Info", "onResp default errCode " + resp.errCode);
				//发送返回
				break;
		}
		finish();
	}


	private void getAccessToken(String code) {
		//获取授权
		StringBuffer loginUrl = new StringBuffer();
		loginUrl.append("https://api.weixin.qq.com/sns/oauth2/access_token")
				.append("?appid=")
				.append(StringConstant.APP_ID)
				.append("&secret=")
				.append(StringConstant.APP_SECRET)
				.append("&code=")
				.append(code)
				.append("&grant_type=authorization_code");

		OkHttpClient okHttpClient = new OkHttpClient();
		Request request = new Request.Builder()
				.url(loginUrl.toString()).build();
		Call call = okHttpClient.newCall(request);
		call.enqueue(new Callback() {
			@Override
			public void onFailure(Call call, IOException e) {
			}

			@Override
			public void onResponse(Call call, Response response) throws IOException {
				String responseStr = response.body().string();
				XLog.e("wx Info","onResponse: --getAccessToken-->>>>" + responseStr);
				try {
					JSONObject jsonObject = new JSONObject(responseStr);
					String access = jsonObject.optString("access_token");
					String openId = jsonObject.optString("openid");
					String refreshToken = jsonObject.optString("refresh_token");
					String unionId = jsonObject.optString("unionid");
					loginInfo.accessToken = access;
					loginInfo.refreshToken = refreshToken;
					loginInfo.unionId = unionId;
					loginInfo.openId = openId;
					loginInfo.code = code;
					loginInfo.loginType = 1;
					String getUserInfo = "https://api.weixin.qq.com/sns/userinfo?access_token=" + access + "&openid=" + openId;
					getInfo(getUserInfo);
				} catch (JSONException e) {
					e.printStackTrace();
				}
			}
		});
	}


	private void getInfo(String url){

		OkHttpClient okHttpClient = new OkHttpClient();
		Request request = new Request.Builder()
				.url(url).build();
		Call call = okHttpClient.newCall(request);
		call.enqueue(new Callback() {
			@Override
			public void onFailure(Call call, IOException e) {
			}

			@Override
			public void onResponse(Call call, Response response) throws IOException {
				String responseStr = response.body().string();
				XLog.e("wx Info","onResponse: " + responseStr);
				//获取个人信息
				try {
					JSONObject jsonObject = new JSONObject(responseStr);
					String openId = jsonObject.optString("openid");
					String nickName = jsonObject.optString("nickname");
					int sex = jsonObject.optInt("sex");
					String iconUrl = jsonObject.optString("headimgurl");
					String unionId = jsonObject.optString("unionid");
					loginInfo.name = nickName;
					loginInfo.gender = sex==1?"m":"f";
					loginInfo.iconUrl = iconUrl;
					loginInfo.unionId = unionId;
					loginInfo.openId = openId;
					BusProvider.getBus().post(loginInfo);
					finish();

				} catch (JSONException e) {
					e.printStackTrace();
				}
			}
		});

	}
}